import { Component } from "@angular/core";
import { NavController, Events, ToastController } from 'ionic-angular';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';
import { NavtiveServeProvider } from '../../../providers/navtiveServe/navtiveServe';


@Component({
    selector: 'page-qrScanner',
    templateUrl: 'qrScanner.html'
})

export class QrScannerPage {
    public title = '扫一扫';
    private frontCamera: boolean = false;
    private light: boolean = false;
    constructor(
        private NavCtrl: NavController,
        private events: Events,
        private qrScanner: QRScanner,
        private navtive: NavtiveServeProvider,
        private toast: ToastController,

    ) {

    }
    ngOnInit() {
        let elements = document.querySelectorAll(".tabbar");
        if (elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display = 'none';
            });
        }
        this.qrScanner.prepare()
            .then((status: QRScannerStatus) => {
                if (status.authorized) {
                    let scanSub = this.qrScanner.scan()
                        .subscribe((text: string) => {

                            let toast = this.toast.create({
                                message: text,
                                duration: 3000,
                                position: 'top'
                            });
                            toast.present();
                            this.qrScanner.hide(); // hide camera preview
                            scanSub.unsubscribe(); // stop scanning
                        });
                    this.qrScanner.show();
                } else if (status.denied) {
                    // camera permission was permanently denied
                    // you must use QRScanner.openSettings() method to guide the user to the settings page
                    // then they can grant the permission from there
                } else {
                    // permission was denied, but not permanently. You can ask for permission again at a later time.
                }
            })
            .catch((e: any) =>

                console.log('Error is', e));
    }
    toggleLight() {
        this.light = !this.light;
        if (this.light) {
            this.qrScanner.disableLight();
        } else {
            this.qrScanner.enableLight();

        }
    }

    toggleCamera() {
        this.frontCamera = !this.frontCamera;
        if (this.frontCamera) {
            this.qrScanner.useBackCamera();
        } else {
            this.qrScanner.useFrontCamera();
        }
    }
    ionViewWillLeave() {
        let elements = document.querySelectorAll(".tabbar");
        if (elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display = 'flex';
            });
        }
    }
}